package com.vancouver.knows.ui.activity.citynews;

import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar.OnMenuItemClickListener;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.pangu.service.ActionException;
import com.pangu.task.mark.ATaskMark;
import com.pangu.util.DeviceUtil;
import com.pangu.util.StringUtil;
import com.vancouver.knows.R;
import com.vancouver.knows.MainApplication.TrackerName;
import com.vancouver.knows.ui.activity.CommentDetailActivity;
import com.vancouver.knows.ui.fragment.citynews.CityNewsPostMainDetailView;
import com.vancouver.knows.ui.fragment.citynews.CityNewsUserPostMainDetailView;
import com.vancouver.knows.ui.view.RichWebView;
import com.vancouver.knows.util.AnalyticsConstants;
import com.vancouver.knows.util.AppUtils;
import com.vancouver.knows.business.Constants;
import com.vancouver.knows.business.bean.CityNewsDetailInfo;
import com.vancouver.knows.business.bean.UserInfo;
import com.vancouver.knows.business.task.mark.FetchCityNewsDetailTaskMark;
import com.vancouver.knows.business.task.mark.UserDeleteArticleTaskMark;
import com.vancouver.knows.business.task.mark.UserDeleteFollowTaskMark;
import com.vancouver.knows.business.task.mark.UserDeleteUpvoteTaskMark;
import com.vancouver.knows.business.task.mark.UserFollowTaskMark;
import com.vancouver.knows.business.task.mark.UserUpvoteTaskMark;

public class CityNewsDetailActivity extends CommentDetailActivity<CityNewsDetailInfo> {

	private Object cityNewsMainDetailView;

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	protected void customizeLoadingView() {
		ImageView loadingImageView = new ImageView(this);
		LinearLayout.LayoutParams linearLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
		loadingImageView.setLayoutParams(linearLayoutParams);
		loadingImageView.setImageResource(R.drawable.loading_city_news_detail);
		loadingImageView.setScaleType(ImageView.ScaleType.FIT_XY);
		((RelativeLayout) loadingView).addView(loadingImageView, 0);
	}

	@Override
	protected void updateInfo() {
		info = bModule.getCacheManager().getCityNewsDetailInfoMap().get(postId);
	}

	@Override
	protected void loadInfo(int type) {
		String userId = bModule.getCacheManager().getUserInfo() == null ? "" : bModule.getCacheManager().getUserInfo()
				.getUserID();
		ATaskMark aTaskMark = bModule.getTaskMarkPool().getFetchCityNewsDetailTaskMark(postId);
		aTaskMark.setTaskType(type);
		bModule.getServiceWrapper().fetchCityNewsDetail(this, aTaskMark, postId, userId);
	}

	@Override
	protected int commentCount() {
		return info.getCommentCount();
	}

	@Override
	protected void subInit() {
		invalidateOptionsMenu();
		toolbar.setOnMenuItemClickListener(new OnMenuItemClickListener() {

			@Override
			public boolean onMenuItemClick(MenuItem item) {
				switch (item.getItemId()) {
				case R.id.menu_item_upvote: {
					upvote();

					Tracker t = imContext.getTracker(TrackerName.APP_TRACKER);
					t.setScreenName(AnalyticsConstants.CUSTOM_EVENT_VALUE_CITYNEWS_DETAIL);
					t.send(new HitBuilders.EventBuilder().setCategory(AnalyticsConstants.CATEGORY_BTN)
							.setAction(AnalyticsConstants.ACTION_ONCLICK)
							.setLabel(AnalyticsConstants.LABEL_CITYNEWS_DETAIL_MENU_UPVOTE).build());
				}
					break;
				/*case R.id.menu_item_follow: {
					Tracker t = imContext.getTracker(TrackerName.APP_TRACKER);
					t.setScreenName(AnalyticsConstants.CUSTOM_EVENT_VALUE_CITYNEWS_DETAIL);
					t.send(new HitBuilders.EventBuilder().setCategory(AnalyticsConstants.CATEGORY_BTN)
							.setAction(AnalyticsConstants.ACTION_ONCLICK)
							.setLabel(AnalyticsConstants.LABEL_CITYNEWS_DETAIL_MENU_FOLLOW).build());

					if (!AppUtils.getLoginStatus(CityNewsDetailActivity.this)) {
						return true;
					}

					UserInfo userInfo = bModule.getCacheManager().getUserInfo();
					if ("Y".equals(info.getUserFollowed())) {
						UserDeleteFollowTaskMark taskMark = bModule.getTaskMarkPool().getUserDeleteFollowTaskMark(
								info.getId());
						bModule.getServiceWrapper().userDeleteFollow(CityNewsDetailActivity.this, taskMark,
								info.getId(), userInfo.getUserID());

					} else {
						UserFollowTaskMark taskMark = bModule.getTaskMarkPool().getUserFollowTaskMark(info.getId());
						bModule.getServiceWrapper().userFollow(CityNewsDetailActivity.this, taskMark, info.getId(),
								userInfo.getUserID());
					}
				}
					break;*/
				case R.id.menu_item_share:
					Tracker t = imContext.getTracker(TrackerName.APP_TRACKER);
					t.setScreenName(AnalyticsConstants.CUSTOM_EVENT_VALUE_CITYNEWS_DETAIL);
					t.send(new HitBuilders.EventBuilder().setCategory(AnalyticsConstants.CATEGORY_BTN)
							.setAction(AnalyticsConstants.ACTION_ONCLICK)
							.setLabel(AnalyticsConstants.LABEL_CITYNEWS_DETAIL_MENU_SHARE).build());

					AppUtils.shareContent(CityNewsDetailActivity.this, info.getTitle(), info.getPermalink(),
							info.getAttachmentImage());
					break;

				case R.id.menu_item_delete:
					UserInfo userInfo = bModule.getCacheManager().getUserInfo();
					if (userInfo != null && info != null && userInfo.getUserID().equals(info.getPostAuthorId())) {
						UserDeleteArticleTaskMark userDeleteArticleTaskMark = bModule.getTaskMarkPool()
								.createUserDeleteArticleTaskMark(info.getId());
						bModule.getServiceWrapper().userDeleteArticle(CityNewsDetailActivity.this,
								userDeleteArticleTaskMark, postId, userInfo.getUserID());
					}
					break;

				default:
					break;
				}
				return true;
			}
		});

		if ("userpost".equals(info.getType())) {
			if (!StringUtil.isEmptyString(info.getSourceUrl())) {
				cityNewsMainDetailView = new RichWebView(this);
				((RichWebView) cityNewsMainDetailView).loadURL(info.getSourceUrl());
				LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0,
						1.0f);
				detailContentLayout.addView((RichWebView)cityNewsMainDetailView, 0, lp);

			} else {
				cityNewsMainDetailView = new CityNewsUserPostMainDetailView(this);
				LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0,
						1.0f);
				detailContentLayout.addView(((CityNewsUserPostMainDetailView) cityNewsMainDetailView).getRootView(), 0, lp);
			}
		} else {
			cityNewsMainDetailView = new CityNewsPostMainDetailView(this);
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0,
					1.0f);
			detailContentLayout.addView(((CityNewsPostMainDetailView) cityNewsMainDetailView).getRootView(), 0, lp);
		}
		invalidateOptionsMenu();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.menu_citynews_detail, menu);
		MenuItem delMenuItem = menu.findItem(R.id.menu_item_delete);
		if (delMenuItem != null) {
			delMenuItem.setVisible(false);
		}

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
		if (info == null) {
			return true;
		}

		MenuItem upvoteMenuItem = menu.findItem(R.id.menu_item_upvote);
		int upvoteIconResId = "Y".equals(info.getUserUpvoted()) ? R.drawable.menu_icon_liked
				: R.drawable.menu_icon_like;
		upvoteMenuItem.setIcon(getResources().getDrawable(upvoteIconResId));

		MenuItem delMenuItem = menu.findItem(R.id.menu_item_delete);
		UserInfo userInfo = bModule.getCacheManager().getUserInfo();
		if (userInfo != null && info != null && userInfo.getUserID().equals(info.getPostAuthorId())) {
			delMenuItem.setVisible(true);
		} else {
			delMenuItem.setVisible(false);
		}

		return true;
	}

	public void upvote() {
//		if (!AppUtils.getLoginStatus(this)) {
//			return;
//		}
//		UserInfo userInfo = bModule.getCacheManager().getUserInfo();
		UserInfo userInfo = bModule.getCacheManager().getUserInfo();
		String userId = null;
		String auid = null;
		if (userInfo != null) {
			userId = userInfo.getUserID();
		} else {
			auid = imContext.getSharedPrefManager().getAuid();
		}

		if ("Y".equals(info.getUserUpvoted())) {
			UserDeleteUpvoteTaskMark taskMark = bModule.getTaskMarkPool().getUserDeleteUpvoteTaskMark(info.getId(),
					"post", info.getId());
			bModule.getServiceWrapper().userDeleteUpvote(CityNewsDetailActivity.this, taskMark, userId, auid,
					info.getId(), "post");

		} else {
			UserUpvoteTaskMark taskMark = bModule.getTaskMarkPool().getUserUpvoteTaskMark(info.getId(), "post",
					info.getId());
			bModule.getServiceWrapper().userUpvote(CityNewsDetailActivity.this, taskMark, userId, auid,
					info.getId(), "post");
		}
	}

	@Override
	public void subHandleMessage(Message msg) {
		super.subHandleMessage(msg);

		switch (msg.what) {
		case Constants.BUSINESS_STATUS_USER_COMMENT_UPVOTE:
		case Constants.BUSINESS_STATUS_USER_DELETE_COMMENT_UPVOTE:
			if (cityNewsMainDetailView instanceof CityNewsPostMainDetailView) {
				((CityNewsPostMainDetailView) cityNewsMainDetailView).subHandleMessage(msg);
			} else if (cityNewsMainDetailView instanceof CityNewsUserPostMainDetailView) {
				((CityNewsUserPostMainDetailView) cityNewsMainDetailView).subHandleMessage(msg);
			}

			break;

		case Constants.BUSINESS_STATUS_DEL_USER_COMMENT:
			loadInfo(ATaskMark.TYPE_REFRESH);
			break;
		}

	}

	@Override
	public void receiveResult(ATaskMark taskMark, ActionException exception, Object trackerResult) {
		super.receiveResult(taskMark, exception, trackerResult);
		if (taskMark instanceof FetchCityNewsDetailTaskMark) {
			updateInfo();
			if (taskMark.getTaskType() == ATaskMark.TYPE_REFRESH) {
				if (cityNewsMainDetailView instanceof CityNewsPostMainDetailView) {
					((CityNewsPostMainDetailView) cityNewsMainDetailView).taskMarkRefreshOver(taskMark);
				} else if (cityNewsMainDetailView instanceof CityNewsUserPostMainDetailView) {
					((CityNewsUserPostMainDetailView) cityNewsMainDetailView).taskMarkRefreshOver(taskMark);
				}

				if (taskMark.getTaskStatus() == ATaskMark.HANDLE_OVER) {
					updateCommentBtn();
				}

			} else {
				if (taskMark.getTaskStatus() == ATaskMark.HANDLE_ERROR) {
					Toast.makeText(this, R.string.load_error, 200).show();
					finish();
					return;

				} else if (taskMark.getTaskStatus() == ATaskMark.HANDLE_OVER) {
					init();
				}
			}

		} else if ((taskMark instanceof UserUpvoteTaskMark || taskMark instanceof UserDeleteUpvoteTaskMark)
				&& taskMark.getTaskStatus() == ATaskMark.HANDLE_OVER) {
			if (cityNewsMainDetailView instanceof CityNewsPostMainDetailView) {
				((CityNewsPostMainDetailView) cityNewsMainDetailView).updateUpvoteLayout();

			} else if (cityNewsMainDetailView instanceof CityNewsUserPostMainDetailView) {
				((CityNewsUserPostMainDetailView) cityNewsMainDetailView).updateUpvoteLayout();
			}
			invalidateOptionsMenu();

		} else if ((taskMark instanceof UserFollowTaskMark || taskMark instanceof UserDeleteFollowTaskMark)
				&& taskMark.getTaskStatus() == ATaskMark.HANDLE_OVER) {
			invalidateOptionsMenu();

		} else if (taskMark instanceof UserDeleteArticleTaskMark && taskMark.getTaskStatus() == ATaskMark.HANDLE_OVER) {
			finish();
		}
	}

}
